/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
export function handleTree(data: Array<any>, id: any, parentId?: any, rootId?: any) {
  id = id || 'id'
  parentId = parentId || 'parentId'
  // eslint-disable-next-line prefer-spread
  rootId = rootId || Math.min.apply(Math, data.map(item => { return item[parentId] })) || 0
  // 对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data))
  // 循环所有项
  const treeData = cloneData.filter((father: any) => {
    const branchArr = cloneData.filter((child: any) => {
      // 返回每一项的子级数组
      return father[id] === child[parentId]
    })
    // eslint-disable-next-line no-unused-expressions
    branchArr.length > 0 ? father.children = branchArr : ''
    // 返回第一层
    return father[parentId] === rootId
  })
  return treeData !== '' ? treeData : data
}

// 递归判断列表，把最后的children设为undefined
export const getTreeData = (data: Array<any>) => {
  if (!data) {
    return
  }
  data.map(item => {
    if (item.children && item.children.length === 0) {
      item.children = undefined
    } else {
      getTreeData(item.children)
    }
  })
  return data
}

/**
 * 根据子级类型查找所有匹配的父级类型
 * id: 子级ID
 * data: 匹配数据
 * prop: 匹配的类型,默认用ID匹配
 */
export function getFathersById(id: any, data: Array<any>, prop = 'id') {
  const arrRes: Array<any> = []
  const rev = (data: any, nodeId: any) => {
    for (let i = 0, length = data.length; i < length; i++) {
      const node = data[i]
      if (node[prop] === nodeId) {
        arrRes.unshift(node[prop])
        return true
      } else {
        if (node.children && node.children.length) {
          if (rev(node.children, nodeId)) {
            arrRes.unshift(node[prop])
            return true
          }
        }
      }
    }
    return false
  }
  rev(data, id)
  return arrRes
}

// 回显数据字典
export function selectDictLabel(datas: any, value: any) {
  const actions: Array<any> = []
  Object.keys(datas).some((key) => {
    if (datas[key].dictValue === ('' + value)) {
      actions.push(datas[key].dictLabel)
      return true
    }
  })
  return actions.join('')
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas: any, value: any, separator: any) {
  const actions: Array<any> = []
  const currentSeparator = undefined === separator ? ',' : separator
  const temp = value.split(currentSeparator)
  Object.keys(value.split(currentSeparator)).some((val) => {
    Object.keys(datas).some((key) => {
      if (datas[key].dictValue === ('' + temp[val])) {
        actions.push(datas[key].dictLabel + currentSeparator)
      }
    })
  })
  return actions.join('').substring(0, actions.join('').length - 1)
}

const mimeMap: Record<string, any> = {
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  zip: 'application/zip'
}
/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res: any, mimeType: string) {
  const aLink = document.createElement('a')
  const blob = new Blob([res.data], { type: mimeMap[mimeType] })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  let fileName = 'csboot'
  if (res.headers) {
    const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
    const contentDisposition = decodeURI(res.headers['content-disposition'])
    const result: any = patt.exec(contentDisposition)
    fileName = result[1]
    // eslint-disable-next-line no-useless-escape
    fileName = fileName.replace(/\"/g, '')
  }
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}
